package com.v5.ik;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gonghui.videomanage.HomeWatcherReceiver;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshWebView;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity {
    private static final int CODE_LOGIN = 0x010;
    private static final int LOGIN_COMPLETE = 0x011;
    private static final int PGAE_TITLE = 0x012;
    private static final int REQUESTPERMISSIONS = 0x013;
    private static final int STARTSAVEIMG = 0x014;
    private static final int GONESPLASH = 0x015;
    private static final int QQRESULT = 0x016;
    private PullToRefreshWebView pullToRefreshWebView;
    private WebView mWebView;
    private IWXAPI mWXAPI;
    private long mClickTime;
    private WebViewClient mWebViewClient;
    private String paySuccessUrl = "";
    private String mShareInfo;
    private JSBridge mJSBridge;
    private TextView mPage_title;
    private FrameLayout mBackBtn;
    private FrameLayout mShareBtn;
    private View splash;
    private TextView tv_show_time;
    private String mCode;
    private OkHttpClient mOkHttpClient = new OkHttpClient();
    private LikeWechatDialog waitDialog;
    private String cur_url = "";
    private long initTime;

    private static final int THUMB_SIZE = 140;
    private String cur_txt;
    private String cur_price;
    private List<String> imgList = new ArrayList<>();
    private ProgressBar pgb_changed;

    private boolean isLogin;
    private String saveImgPath;
    private HomeWatcherReceiver mHomeKeyReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this);
        strategy.setAppVersion("IK_Beta5");      //App的版本
        strategy.setAppPackageName("com.v5.ik");  //App的包名
        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog;
        Beta.strUpgradeDialogCancelBtn = "";
        Beta.smallIconId = R.mipmap.notification_small;
        Bugly.init(this, "4f738d3834", true, strategy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this);
        initWx();

        mHomeKeyReceiver = new HomeWatcherReceiver();
        registerReceiver(mHomeKeyReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

        splash = findViewById(R.id.splash);
        initTime = System.currentTimeMillis();
        tv_show_time = (TextView) findViewById(R.id.tv_show_time);
        tv_show_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                splash.setVisibility(View.GONE);
            }
        });
        pullToRefreshWebView = (PullToRefreshWebView) findViewById(R.id.webview);
        pullToRefreshWebView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<WebView>() {
            @Override
            public void onRefresh(PullToRefreshBase<WebView> refreshView) {
                refreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pullToRefreshWebView.onRefreshComplete();
                    }
                }, 0);
            }
        });
        mWebView = pullToRefreshWebView.getRefreshableView();

        mPage_title = (TextView) findViewById(R.id.page_title);
        mBackBtn = (FrameLayout) findViewById(R.id.back_btn);
        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                webGoBack();
                onBackPressed();
            }
        });

        mShareBtn = (FrameLayout) findViewById(R.id.share_btn);
        mShareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mShareInfo != null) {
                    JSONObject shareObj;
                    try {
                        shareObj = new JSONObject(mShareInfo);
                        if (!shareObj.has("isLogin") || !shareObj.getBoolean("isLogin")) {
                            goLogin();
                            return;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    new ShareBoard().show(getWindow().getDecorView());
                }
            }
        });

        WebSettings settings = mWebView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptEnabled(true);
        final String ua = settings.getUserAgentString();
        settings.setUserAgentString(ua + "; ZYMALLAPP");

        pgb_changed = (ProgressBar) findViewById(R.id.pgb_changed);
        final WebChromeClient webChromeClient = new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                Log.i("qwe", "onProgressChanged: " + newProgress);

                pgb_changed.setProgress(newProgress);
                if (newProgress == 100)
                    pgb_changed.postDelayed(new Thread() {
                        @Override
                        public void run() {
                            pgb_changed.setVisibility(View.GONE);
                            if (isLogin) {
                                if (waitDialog != null && waitDialog.isShowing()) {
                                    waitDialog.dismiss();
                                    isLogin = false;
                                }
                            }

                        }
                    }, 200);
                else
                    pgb_changed.setVisibility(View.VISIBLE);
            }


        };
        mWebView.setWebChromeClient(webChromeClient);

        mWebViewClient = new WebViewClient() {
            @SuppressWarnings("deprecation")
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i("qwe", "url: " + url);
                // 获取上下文, H5PayDemoActivity为当前页面
                final Activity context = MainActivity.this;
                // ------  对alipays:相关的scheme处理 -------
                if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(context)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        context.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                }
                // ------- 处理结束 -------

                //打开QQ
                if (url.startsWith("mqqwpa://")) {
                    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivityForResult(in, QQRESULT);
                    return true;
                }

                if (!(url.startsWith("http") || url.startsWith("https"))) {
                    return true;
                }

                if (url.contains("LoginView")) {
                    if (url.contains("from=APP")) {
                        view.loadUrl(url);
                    } else {
                        goLogin();
                    }
                    return true;
                }

                if (url.contains("Shop/Share")) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    String CookieStr = cookieManager.getCookie(url);
                    Log.i("qwe", "Cookies = " + CookieStr);
                    String customer = "";
                    for (String str : CookieStr.split(";")) {
                        if (str.contains("CustId"))
                            customer = str.substring(("CustId" + Constants.ORG + "=").length() + 1);
                    }
                    getSupportFragmentManager().beginTransaction().add(R.id.fl_inner, new PYQFragment(customer), "PYQFragment").addToBackStack(null).commit();

                    mPage_title.setText("朋友圈素材");
                    return true;
                }

                view.loadUrl(url);
                return true;
            }

            //            @Override
//            public void onLoadResource(WebView view, String url) {
//                Log.i("qwe", "onLoiadResource :: " + url);
//            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.i("qwe", "onPageStarted");
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i("qwe", "onPageFinished url:" + url);
                if ("about:blank".equals(url))
                    return;

                if (!url.contains("LoginView")) {
                    cur_url = url;
                    Log.i("qwe", "cur_url:" + cur_url);
                } else if (!url.contains("from=APP")) {
                    return;
                }

                mWebView.loadUrl("javascript:getShareInfoForAPP();");
                if (url.contains("ProductInfo")) {
                    imgList.clear();
                    mWebView.loadUrl("javascript:$('.swiper-slide').each(function(){window.JSBridge.getImgList($(this).find('img').attr('src'))});");
                    mWebView.loadUrl("javascript:window.JSBridge.showSource(jsonsku_price[0].ItemName,jsonsku_price[0].Price);");
                }
                mWebView.loadUrl("javascript:window.JSBridge.getTitle($('title').text())");

                if (url.contains("QR/QRCodePropu?cust=")) {
                    mWebView.loadUrl("javascript:$('#qrimg').click(function(){window.JSBridge.saveImg($(this).attr('src'))});");
                }

                if (isHomePage(url)) {
                    mBackBtn.setVisibility(View.INVISIBLE);
                    pullToRefreshWebView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    mWebView.clearHistory();
                } else {
                    mBackBtn.setVisibility(View.VISIBLE);
                    pullToRefreshWebView.setMode(PullToRefreshBase.Mode.DISABLED);
                }
                showHideShareBtn(url);
            }
        };
        mWebView.setWebViewClient(mWebViewClient);
        mJSBridge = new JSBridge();
        mWebView.addJavascriptInterface(mJSBridge, "JSBridge");
        mWebView.loadUrl(Constants.INDEX);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.sendEmptyMessage(GONESPLASH);
    }

    private String getMyurl(String url) {
        if (url.isEmpty()) {
            url = Constants.INDEX;
        }
        String str;
        try {
            str = url.substring(Constants.HTTP.length());
        } catch (StringIndexOutOfBoundsException e) {
            str = "/Home/Index";
        }
        if (str.startsWith("//")) {
            str = str.substring(1);
        }
        return str;
    }

    private void initWx() {
        mWXAPI = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        mWXAPI.registerApp(Constants.APP_ID);
    }

    private void showHideShareBtn(String url) {
        if (url.contains("Cart") || url.contains("Shop") || url.contains("Customer") || url.contains("Order") || url.contains("alipay")) {
            mShareBtn.setVisibility(View.GONE);
        } else {
            mShareBtn.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEvent(BaseResp baseResp) {
        // 微信支付
        if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            switch (baseResp.errCode) {
                case 0: // 成功	展示成功页面
                    showToast("支付成功");
                    break;
                case -1://错误	可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
                    showToast("支付失败:" + baseResp.errStr);
                    break;
                case -2://用户取消	无需处理。发生场景：用户不支付了，点击取消，返回APP。
                    showToast("支付已取消");
                    break;
            }
            mWebView.loadUrl(paySuccessUrl);
        }
        // 微信分享
        else if (baseResp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    showToast("分享成功");
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    showToast("分享失败");
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    showToast("分享已取消");
                    break;
                default:
                    showToast("分享出错");
                    break;
            }
        }

        // 微信登录
        else if (baseResp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            Log.i("qwe", "微信登录RESP main");
            if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
                waitDialog = new LikeWechatDialog(this, "登录中...");
                waitDialog.show();
                isLogin = true;
                mCode = ((SendAuth.Resp) baseResp).code;
                getAccessToken();
            }
        }
    }

    private void getAccessToken() {
        StringBuilder sb = new StringBuilder()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
                .append(Constants.APP_ID)
                .append("&secret=")
                .append(Constants.APP_SECRET)
                .append("&code=")
                .append(mCode)
                .append("&grant_type=authorization_code");
        Request request = new Request.Builder().url(sb.toString()).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (waitDialog != null && waitDialog.isShowing()) {
                    waitDialog.dismiss();
                }
                showToast("网络繁忙，登录失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resp = response.body().string();
                try {
                    final JSONObject obj = new JSONObject(resp);
                    if (obj.has("errcode")) {
                        if (waitDialog != null && waitDialog.isShowing()) {
                            waitDialog.dismiss();
                        }
                        showToast("微信信息获取失败");
                        return;
                    }

                    // 获取用户个人信息
                    String access_token = obj.getString("access_token");
                    String openid = obj.getString("openid");
                    getUserinfo(access_token, openid);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (null != mHomeKeyReceiver) {
            unregisterReceiver(mHomeKeyReceiver);
        }
        Log.i("qwe", "onDestroy: Main");
        mWebView.clearCache(true);
        super.onDestroy();
    }

    private void getUserinfo(String access_token, String openid) {
        final StringBuilder sb = new StringBuilder()
                .append("https://api.weixin.qq.com/sns/userinfo?access_token=")
                .append(access_token)
                .append("&openid=")
                .append(openid);
        Request request = new Request.Builder().url(sb.toString()).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (waitDialog != null && waitDialog.isShowing()) {
                    waitDialog.dismiss();
                }
                showToast("网络繁忙，登录失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String resp = response.body().string();
                try {
                    final JSONObject obj = new JSONObject(resp);
                    // 获取用户信息错误
                    if (obj.has("errcode")) {
                        if (waitDialog != null && waitDialog.isShowing()) {
                            waitDialog.dismiss();
                        }
                        showToast("微信信息获取失败");
                        return;
                    }

                    Message msg = mHandler.obtainMessage();
                    msg.obj = resp;
                    msg.what = LOGIN_COMPLETE;
                    mHandler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == LOGIN_COMPLETE) {
                String info = "";
                try {
                    info = URLEncoder.encode((String) msg.obj, "utf-8");
                    Log.i("qwe", "info: " + info);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String url;
                if (cur_url.isEmpty()) {
                    url = Constants.INDEX + "?wechatlogin=" + info;
                } else {
                    if (cur_url.contains("?")) {
                        url = cur_url + "&wechatlogin=" + info;
                    } else {
                        url = cur_url + "?wechatlogin=" + info;
                    }
                }
                mWebView.loadUrl(url);
                Log.i("qwe", "login url: " + url);
            }
            if (msg.what == PGAE_TITLE) {
                String title = (String) msg.obj;
                Log.i("qwe", "getTitle title: " + title);
                String url = mWebView.getUrl();
                if (isHomePage(url)) {
                    JSONObject shareObj;
                    try {
                        shareObj = new JSONObject(mShareInfo);
                        if (!shareObj.has("isLogin") || !shareObj.getBoolean("isLogin")) {
                            title = getString(R.string.app_name);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (url.contains("ProductInfo") && !url.contains("LoginView")) {
                    title = "商品详情";
                }
                Log.i("qwe", "setTitle" + title);
                mPage_title.setText(title);
            }

            if (msg.what == GONESPLASH) {
                int time = 3 - (int) (System.currentTimeMillis() - initTime) / 1000;
                if (time > 0 && splash.getVisibility() == View.VISIBLE) {
                    mHandler.sendEmptyMessageDelayed(GONESPLASH, 500);
                    tv_show_time.setText("跳过 " + time);
                } else {
                    splash.setVisibility(View.GONE);
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CODE_LOGIN) {
            if (resultCode == RESULT_OK) {
                Bundle extras = data.getExtras();
                String page = extras.getString("page");
                if ("login".equals(page)) {
                    String url = String.format(Constants.LOGIN_URL, getMyurl(cur_url));
                    Log.i("qwe", "url LoginView : " + url);
                    mWebView.loadUrl(url);
                }
            }
        }
        if (requestCode == QQRESULT && !isHomePage(cur_url)) {
            mWebView.loadUrl(Constants.INDEX);
        }
    }

    @Override
    public void onBackPressed() {
        if (splash.getVisibility() == View.VISIBLE)
            return;

        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            super.onBackPressed();
            mPage_title.setText("我的商店");
            return;
        }

        webGoBack();
    }

    public void close() {
        if (mClickTime == 0 || System.currentTimeMillis() - mClickTime > 1500) {
            mClickTime = System.currentTimeMillis();
            showToast("再按一次退出应用");
        } else {
            finish();
        }

    }

    private void goLogin() {
        Log.i("qwe", "goLogin:");
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivityForResult(intent, CODE_LOGIN);
    }

    public void shareToWeChat(int scene) {
        if (mShareInfo == null) {
            return;
        }
        JSONObject shareObj = null;
        String url = null;
        String title = null;
        String summary = null;
        String img = null;
        try {
            shareObj = new JSONObject(mShareInfo);
            url = shareObj.getString("shareUrl");
            title = shareObj.getString("shareTitle");
            summary = shareObj.getString("shareDesc");
            img = shareObj.getString("shareImg");
        } catch (JSONException e1) {
            e1.printStackTrace();
            return;
        }

        final SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        switch (scene) {
            case 1: //微信好友
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case 2: //朋友圈
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;

        final WXMediaMessage message = new WXMediaMessage(webpage);

        message.title = title;
        message.description = summary;

        // 没有缩略图
        if (TextUtils.isEmpty(img)) {
            req.message = message;
            mWXAPI.sendReq(req);
            return;
        }
        // 有缩略图
        final String finalImg = img;
        new AsyncTask<String, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(String... params) {
                Bitmap bmp = Utils.downloadImg(finalImg);
                Bitmap thumbBmp = null;
                if (bmp != null) {
                    thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                    bmp.recycle();
                }
                return thumbBmp;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap == null) {
                    message.setThumbImage(bitmap);
                } else {
                    message.thumbData = Utils.bmpToByteArray(bitmap, true);  // 设置缩略图
                    Log.i("qwe", "bitmap: " + bitmap.getWidth() + "   " + bitmap.getHeight() + "   " + message.thumbData.length);
                }
                req.message = message;
                if (!req.checkArgs()) {
                    showToast("无法分享");
                    return;
                }
                mWXAPI.sendReq(req);
            }
        }.execute();

    }

    private void webGoBack() {
        if (isHomePage(mWebView.getUrl())) {
            close();
        } else if (!mWebView.canGoBack()) {
            mWebView.loadUrl(Constants.INDEX);
        } else {
            if (mWebView.getUrl().contains("LoginView") || mWebView.getUrl().contains("alipay")) {
                mWebView.goBack();
                return;
            }

            WebBackForwardList webBackForwardList = mWebView.copyBackForwardList();
            int currentIndex = webBackForwardList.getCurrentIndex();
            Log.i("qwe", "webGoBack currentIndex: " + currentIndex);
            int steps = 0;
            String url;
            Log.i("qwe", "webGoBack getSize: " + webBackForwardList.getSize());
            for (int i = 0; i < webBackForwardList.getSize(); i++) {
                url = webBackForwardList.getItemAtIndex(i).getUrl();
                Log.i("qwe", "webGoBack url: " + url);
                if ("about:blank".equals(url))
                    continue;

                if (isHomePage(url))
                    continue;

                try {
                    if (url.substring(url.indexOf("/", (Constants.HTTP + "/").length())).contains(mWebView.getUrl().substring(mWebView.getUrl().indexOf("/", (Constants.HTTP + "/").length()))) || mWebView.getUrl().substring(mWebView.getUrl().indexOf("/", (Constants.HTTP + "/").length())).contains(url.substring(url.indexOf("/", (Constants.HTTP + "/").length())))) {
                        steps = i - currentIndex - 1;
                        break;
                    }
                } catch (StringIndexOutOfBoundsException e) {
                    mWebView.loadUrl(Constants.INDEX);
                    return;
                }
            }

            WebHistoryItem itemAtIndex = webBackForwardList.getItemAtIndex(currentIndex + steps);
            if (itemAtIndex == null) {
                mWebView.loadUrl(Constants.INDEX);
                return;
            } else {
                url = webBackForwardList.getItemAtIndex(currentIndex + steps).getUrl();
                while (url.contains("LoginView")) {
                    steps--;
                    url = webBackForwardList.getItemAtIndex(currentIndex + steps).getUrl();
                }
            }

            Log.i("qwe", "webGoBack steps: " + steps);

            mWebView.goBackOrForward(steps);
        }
    }

    private boolean isHomePage(String url) {
        if (url == null)
            return false;

        return (url.contains("Home/Index") && !url.contains("LoginView")) || url.matches(Constants.HTTP + "/\\w{6,14}") || url.matches(Constants.HTTP + "/\\w{6,14}/") || url.matches(Constants.HTTP + "/\\w{6,14}\\?wechatlogin.*") || url.matches(Constants.HTTP + "/\\w{6,14}/\\?wechatlogin.*") || url.equals(Constants.INDEX);
    }

    private class JSBridge {
        @JavascriptInterface
        public void requestLogin() {
            Log.i("qwe", "requestLogin: ");
            goLogin();
        }

        @JavascriptInterface
        public void setShareInfo(String shareInfo) {
            mShareInfo = shareInfo;
        }

        @JavascriptInterface
        public void requestWxPay(String data) {
            Log.i("qwe", "requestWxPay: " + data);
            try {
                JSONObject obj = new JSONObject(data);
                PayReq req = new PayReq();
                req.appId = obj.getString("appId");
                req.partnerId = obj.getString("partnerId");
                req.nonceStr = obj.getString("nonceStr");
                req.prepayId = obj.getString("prepayId");
                req.timeStamp = obj.getString("timeStamp");
                req.sign = obj.getString("sign");
                req.packageValue = obj.getString("package");
                paySuccessUrl = obj.getString("successUrl");

                if (!req.checkArgs()) {
                    showToast("支付信息错误");
                    return;
                }

                mWXAPI.sendReq(req);
            } catch (JSONException e) {
                e.printStackTrace();
                showToast("支付异常");
            }
        }

        @JavascriptInterface
        public void getImgList(String img) {
            Log.i("qwe", "getImgList: " + img);
            imgList.add(img);
        }

        @JavascriptInterface
        public void showSource(String txt, float price) {
            cur_txt = txt.trim();
            cur_price = new DecimalFormat(".00").format(price);
            Log.i("qwe", "txt: " + cur_txt);
            Log.i("qwe", "price: " + cur_price);
        }

        @JavascriptInterface
        public boolean getParme(String json, String img) {
            Log.i("qwe", "getParme json: " + json);
            Log.i("qwe", "getParme img: " + img);
            return true;
        }

        @JavascriptInterface
        public void getTitle(String title) {
            if (mShareInfo == null) {
                return;
            }
            Message message = mHandler.obtainMessage(PGAE_TITLE);
            message.obj = title;
            mHandler.sendMessage(message);
        }

        @JavascriptInterface
        public void saveImg(String imgPath) {
            saveImgPath = imgPath;
            Log.i("qwe", "saveImg: " + saveImgPath);
            if (saveImgPath == null) {
                return;
            }
            AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
            dialog.setTitle("保存这张图片吗？");
            dialog.setNegativeButton("取消", null);
            dialog.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.M)
                @Override
                public void onClick(DialogInterface dialogInterface, final int i) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STARTSAVEIMG);
                    } else {
                        startSaveImg();
                    }
                }
            });
            dialog.show();
        }
    }

    private void startSaveImg() {
        final LikeWechatDialog likeWechatDialog = new LikeWechatDialog(MainActivity.this, "正在保存...");
        likeWechatDialog.show();
        new AsyncTask<String, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(String... params) {
                Bitmap bmp = Utils.downloadImg(saveImgPath);
                if (bmp != null) {
                    return Utils.writeImg(bmp);
                }
                return false;
            }

            @Override
            protected void onPostExecute(Boolean b) {
                likeWechatDialog.dismiss();
                showToast(b ? "保存成功" : "保存失败");
            }
        }.execute();
    }

    public class ShareBoard extends PopupWindow implements View.OnClickListener {
        public ShareBoard() {
            initView();
        }

        private void initView() {
            View rootView = LayoutInflater.from(MainActivity.this).inflate(R.layout.share_board, null);
            rootView.findViewById(R.id.wechat).setOnClickListener(this);
            rootView.findViewById(R.id.wechat_circle).setOnClickListener(this);
            View v_tuwen = rootView.findViewById(R.id.tuwenfenxiang);
            v_tuwen.setOnClickListener(this);
            if (cur_url.contains("ProductInfo")) {
                v_tuwen.setVisibility(View.VISIBLE);
            } else {
                v_tuwen.setVisibility(View.GONE);
            }
            rootView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
            rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
            setContentView(rootView);
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setBackgroundDrawable(new ColorDrawable(0x88000000));
            setTouchable(true);
            setAnimationStyle(android.R.style.Animation_InputMethod);
        }

        @Override
        public void onClick(View v) {
            if (!mWXAPI.isWXAppInstalled()) {
                showToast("请先安装微信");
                return;
            }

            int id = v.getId();
            dismiss();
            // 微信好友
            if (id == R.id.wechat) {
                shareToWeChat(1);
            }
            // 朋友圈
            else if (id == R.id.wechat_circle) {
                shareToWeChat(2);
            } else if (id == R.id.tuwenfenxiang) {
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
//                    if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    //你已经拒绝过一次了
//                    }
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUESTPERMISSIONS);
                } else {
                    shareFromWeChat();
                }
            }
        }

        public void show(View parent) {
            showAtLocation(parent, Gravity.CENTER, 0, 0);
        }
    }

    private void shareFromWeChat() {
        final LikeWechatDialog likeWechatDialog = new LikeWechatDialog(MainActivity.this, "请稍等...");
        likeWechatDialog.show();
        new AsyncTask<String, Void, List<Bitmap>>() {
            @Override
            protected List<Bitmap> doInBackground(String... params) {
                List<Bitmap> bitmapList = new ArrayList<>();
                List<String> imgSubList;
                if (imgList.size() > 3) {
                    imgSubList = imgList.subList(1, imgList.size() - 1);
                } else {
                    imgSubList = imgList.subList(0, imgList.size());
                }
                for (int i = 0; i < imgSubList.size(); i++) {
                    bitmapList.add(Utils.downloadImg(imgSubList.get(i)));
                }
                return bitmapList;
            }

            @Override
            protected void onPostExecute(List<Bitmap> bitmapList) {
                if (bitmapList == null || bitmapList.size() == 0)
                    return;

                Intent shareIntent = new Intent();
                ComponentName componentName = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                shareIntent.setComponent(componentName);
                shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                shareIntent.putExtra("Kdescription", "自从有了IK这个美甲大师，[鼓掌][鼓掌][鼓掌]我就开始10天换一次新花样，舒适环保，搭配不同衣服，最主要经济实惠，78元可以做双手两次、脚丫一次[强][强][强]一大波美手都在路上…\uD83E\uDD17 DIY美甲一直很有型\ue40a，法国Ik真心方便");
                shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);

                ArrayList<Uri> uris = new ArrayList<>();
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ik");
                if (!file.isDirectory()) {
                    file.mkdirs();
                }
                try {
                    for (int i = 0; i < bitmapList.size(); i++) {
                        File outFile = new File(file.getPath() + "/" + System.currentTimeMillis() + ".jpg");
                        OutputStream os = new FileOutputStream(outFile);
                        Bitmap bitmap;
                        //仅第一张图添加二维码
//                        if (i == 0)
//                            bitmap = createShareBitmap(bitmapList.get(i));
//                        else
//                            bitmap = bitmapList.get(i);

                        //所有图添加二维码
                        bitmap = createShareBitmap(bitmapList.get(i));

                        if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os)) {
                            uris.add(Uri.fromFile(outFile));
                        }
                        os.close();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                shareIntent.setType("image/*");
                startActivity(shareIntent);
                likeWechatDialog.dismiss();
            }
        }.execute();
    }

    private Bitmap createShareBitmap(Bitmap bitmap) {
        View view = View.inflate(MainActivity.this, R.layout.tuwen_layout, null);
        ViewGroup.LayoutParams viewParams = new ViewGroup.LayoutParams(640, 1137);
        view.setLayoutParams(viewParams);
        ImageView img = (ImageView) view.findViewById(R.id.iv_img);
        img.setImageBitmap(bitmap);
        TextView text = (TextView) view.findViewById(R.id.tv_text);
        text.setText(cur_txt);
        TextView price = (TextView) view.findViewById(R.id.tv_price);
        price.setText(cur_price);
        ImageView rq = (ImageView) view.findViewById(R.id.iv_rq);
        JSONObject shareObj;
        try {
            shareObj = new JSONObject(mShareInfo);
            if (shareObj.has("shareUrl")) {
                rq.setImageBitmap(Utils.createQRImage(shareObj.getString("shareUrl")));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return Utils.convertViewToBitmap(view);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            Toast.makeText(getApplicationContext(), "你拒绝了相关的权限！", Toast.LENGTH_SHORT).show();
        } else {
            switch (requestCode) {
                case REQUESTPERMISSIONS:
                    shareFromWeChat();
                    break;
                case STARTSAVEIMG:
                    startSaveImg();
                    break;
            }
        }
    }
}
